<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .list {
            height: 150px;
            overflow: auto;
        }
        .news {
            height: 29px;
            border-bottom: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="app"></div>
 
    <script type="text/javascript" src="../js/17.0.0.1/react.development.js"></script>
    <script type="text/javascript" src="../js/17.0.0.1/react-dom.development.js"></script>
    <script type="text/javascript" src="../js/17.0.0.1/babel.min.js"></script>
    
    <script type="text/babel">
        class Demo extends React.Component {
            state = {newsArr:[]}

            componentDidMount() {
                setInterval(() => {
                    // 获取状态
                    let {newsArr} = this.state
                    const news = '列表'+(newsArr.length+1)
                    // 更新状态
                    this.setState({newsArr:[news,...newsArr]})
                }, 1000);
            }
            getSnapshotBeforeUpdate() {
                return this.refs.list.scrollHeight
            }
            componentDidUpdate(preProps,preState,height) {
                this.refs.list.scrollTop += this.refs.list.scrollHeight - height
            }
            render() {
                return (
                    <div>
                        <ul className="list" ref="list">
                            {
                                this.state.newsArr.map((n,index) => {
                                    return <li key={index} className="news">{n}</li>
                                })
                            } 
                        </ul>
                    </div>
                )
            }
        }
        ReactDOM.render(<Demo/>,document.querySelector("#app"))
        
    </script>
</body>
</html>